package servlet;

import java.io.IOException;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import entity.User;
import session.UserDao;


/**
 * Kontroler koji vrši logovanje korisnika na sistem.
 * Ako se korisnik postoji, i aktivan je, smesti u session
 * njene atribute, tj klasu User. 
 * @author rigo & jung
 *
 */
public class Login extends HttpServlet {
	private static final long serialVersionUID = 531395085730230215L;
	
	@EJB
	protected UserDao userDao ;
	 
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		try{
			String email = null;
			String password = null;

			email = request.getParameter("email");
			password = request.getParameter("password");
			
			/* Provera da li su sva polja popunjena
			 * ako ne vraca korisnika na login stranu
			 */
			if ((email==null)||(email.equals(""))||(password==null)||(password.equals(""))){
				response.sendRedirect(response.encodeRedirectURL("./login.jsp"));
				return; 
			}
			if(userDao.login(email, password)!=null){
				User user = userDao.login(email, password);
				HttpSession session = request.getSession(true);
				session.setAttribute("user", user);
				if(user.getType()=='A'){
					request.setAttribute("pendingUsers", userDao.getPendingUsers());
				}
				getServletContext().getRequestDispatcher("/main.jsp").forward(request, response);
				return;
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
		response.sendRedirect(response.encodeRedirectURL("./login.jsp"));
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}
